package su.msk.jet.team01.chatik.server;

import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import su.msk.jet.team01.chatik.server.data.Client;
import su.msk.jet.team01.chatik.server.data.Feedback;

public class NetworkClient implements Feedback {

	private static Logger logger = LoggerFactory.getLogger(NetworkClient.class);

	private final Server server;
	private final Socket socket;
	private final Client client;

	private ClientInputHandler input;
	private ClientOutputHandler output;

	public NetworkClient(final Server server, final Socket socket) {
		this.server = server;
		this.socket = socket;

		client = new Client(this);
	}
	
	@Override
	public final void disconnect() {
		server.disconnectNetworkClient(this);
	}

	public ClientInputHandler getInput() {
		return input;
	}
	
	public ClientOutputHandler getOutput() {
		return output;
	}
	
	public Socket getSocket() {
		return socket;
	}
	
	public final Client getClient() {
		return client;
	}

	public String getIP() {
		String orig = socket.getRemoteSocketAddress().toString();
		return orig.substring(1, orig.length());
	}

	@Override
	public void sendMessage(final String msg) {
		output.sendMessage(msg);
	}

	public void start() {
		try {
			output = new ClientOutputHandler(socket.getOutputStream(), this);
			input = new ClientInputHandler(socket.getInputStream(), this);
		} catch (SocketException ex) {
			server.disconnectNetworkClient(this);
			logger.warn(ex.getMessage(), ex);
			return;
		} catch (IOException ex) {
			server.disconnectNetworkClient(this);
			logger.warn(ex.getMessage(), ex);
			return;
		}
		
		input.start();
		output.start();
	}
}
